﻿using Facebook;
using FriendAnalyzer.Infrastructure.Facebook.DataAccess;
using FriendAnalyzer.Infrastructure.Facebook.Interfaces;
using FriendAnalyzer.Infrastructure.Facebook.Repositories;
using System;

namespace FriendAnalyzer.Infrastructure.Facebook
{
    public class AuthenticationResult : IAuthenticationResult
    {
        private FacebookConfig _settings;
        private FacebookOAuthResult _token;
        private string _errorMessage;

        internal AuthenticationResult(FacebookConfig settings, FacebookOAuthResult token)
        {
            _settings = settings;
            _token = token;
        }
        internal AuthenticationResult(string errorMessage)
        {
            _errorMessage = errorMessage;
        }

        public bool IsSuccesful()
        {
            if (_token != null)
            {
                return _token.IsSuccess;
            }

            return false;
        }
        public IFriendsAPI GetAPI()
        {
            if (_token.IsSuccess)
            {
                var client = new FacebookClient(_token.AccessToken);
                var connection = new FacebookConnection(client);
                var repository = new FriendRepository(connection);

                return new FriendsAPI(repository);
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
        public string GetErrorMessage()
        {
            if (_token != null)
            {
                return _token.ErrorDescription;
            }
            else
            {
                return _errorMessage;
            }
        }
    }
}